package com.example.dw.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 管理端JWT工具类
 * @author system
 * @since 2024-01-01
 */
@Slf4j
@Component
public class AdminJwtUtil {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    // 管理端token前缀标识
    private static final String ADMIN_TOKEN_PREFIX = "ADMIN_";

    /**
     * 生成管理端token
     */
    public String generateAdminToken(Integer adminId, String adminUsername, String role) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expiration);
        
        Algorithm algorithm = Algorithm.HMAC256(secret);
        return JWT.create()
                .withSubject(ADMIN_TOKEN_PREFIX + adminUsername)
                .withClaim("adminId", adminId)
                .withClaim("adminUsername", adminUsername)
                .withClaim("role", role)
                .withClaim("tokenType", "admin")
                .withIssuedAt(now)
                .withExpiresAt(expiryDate)
                .sign(algorithm);
    }

    /**
     * 验证管理端token
     */
    public boolean validateAdminToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            
            // 验证是否为管理端token
            String tokenType = jwt.getClaim("tokenType").asString();
            return "admin".equals(tokenType);
        } catch (JWTVerificationException exception) {
            log.error("管理端Token验证失败: {}", exception.getMessage());
            return false;
        }
    }

    /**
     * 从token中获取管理员ID
     */
    public Integer getAdminIdFromToken(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("adminId").asInt();
        } catch (JWTDecodeException exception) {
            log.error("管理端Token解析失败: {}", exception.getMessage());
            return null;
        }
    }

    /**
     * 从token中获取管理员用户名
     */
    public String getAdminUsernameFromToken(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("adminUsername").asString();
        } catch (JWTDecodeException exception) {
            log.error("管理端Token解析失败: {}", exception.getMessage());
            return null;
        }
    }

    /**
     * 从token中获取管理员角色
     */
    public String getRoleFromToken(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("role").asString();
        } catch (JWTDecodeException exception) {
            log.error("管理端Token解析失败: {}", exception.getMessage());
            return null;
        }
    }

    /**
     * 获取token的过期时间
     */
    public Date getExpirationDateFromToken(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getExpiresAt();
        } catch (JWTDecodeException exception) {
            log.error("管理端Token解析失败: {}", exception.getMessage());
            return null;
        }
    }

    /**
     * 判断token是否过期
     */
    public boolean isTokenExpired(String token) {
        Date expiration = getExpirationDateFromToken(token);
        return expiration != null && expiration.before(new Date());
    }

    /**
     * 检查是否为管理端token
     */
    public boolean isAdminToken(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            String tokenType = jwt.getClaim("tokenType").asString();
            return "admin".equals(tokenType);
        } catch (Exception e) {
            return false;
        }
    }
} 